package com.han.verifycode.enums;

import com.han.verifycode.CodeConfig;
import com.han.verifycode.VerifyCode;
import com.han.verifycode.ver.exact.CalcNumCode;
import com.han.verifycode.ver.exact.FixedKeyPairCode;
import com.han.verifycode.ver.exact.TextCode;
import com.han.verifycode.ver.point.IdiomPointCode;
import com.han.verifycode.ver.point.PicturePointCode;
import com.han.verifycode.ver.point.PicturePuzzleCode;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.lang.reflect.Field;

@Getter
@AllArgsConstructor
public enum VerifyCodeEnum {
    Text(1, "字母数字", TextCode.class),
    FixedKeyPair(2, "固定搭配", FixedKeyPairCode.class),
    CalcNum(3, "数学计算", CalcNumCode.class),
    IdiomPoint(4, "成语多点识别", IdiomPointCode.class),
    PicturePoint(5, "图片内容识别", PicturePointCode.class),
    PicturePuzzle(6, "拼图", PicturePuzzleCode.class);
    private Integer code;
    private String desc;
    private Class<? extends VerifyCode> type;


    public static VerifyCode getByCode(Integer code) {
        if (code == null) {
            return null;
        }
        for (VerifyCodeEnum en : VerifyCodeEnum.values()) {
            if (code == en.code) {
                return getVerifyInstance(en);
            }
        }
        return null;
    }

    public static VerifyCode getByName(String name) {
        if (name == null) {
            return null;
        }
        for (VerifyCodeEnum en : VerifyCodeEnum.values()) {
            if (name.equals(en.name())) {
                return getVerifyInstance(en);
            }
        }
        return null;
    }

    /**
     * 根据配置类型
     *
     * @param config
     * @return
     */
    public static VerifyCodeEnum getByConfType(CodeConfig config) {
        for (VerifyCodeEnum e : VerifyCodeEnum.values()) {
            Class<? extends VerifyCode> typ = e.getType();
            Field[] fields = typ.getDeclaredFields();
            for (Field f : fields) {
                Class<?> gtype = f.getType();
                if (gtype == config.getClass()) {
                    return e;
                }
            }
        }
        return null;
    }

    public static VerifyCode getVerifyInstance(VerifyCodeEnum en) {
        if (en == null) {
            return null;
        }
        Class<? extends VerifyCode> clazz = en.getType();
        try {
            return clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}
